<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <script type="text/javascript" src="js/jquery.js"></script>
    <script type="text/javascript" src="js/oauth.js"></script>
    <script type="text/javascript" src="js/sha1.js"></script>
    <script type="text/javascript" src="js/orkut_lib.js"></script>
    <script type="text/javascript">
    var orkut;
    
    function initBg() {
        orkut = new Orkut();
        registerListeners();
        
        checkIcon();
        
        window.setInterval('apoller()', 5000 * 60 ) // 5 min 
        
    }
    
    /**
    Handles first 3lo auth step. Request the token and redirect to google´s website
    */
    function auth() 
    {
        // just a sanity check in case someone drops the keys
        if(localStorage['authenticated'] && (!localStorage['oauth_token'] || !localStorage['oauth_token_secret'])) {
            delete localStorage['authenticated'];
        }
    
        // if not authenticated, then go and auth
        if(!localStorage['authenticated'])
        {
            orkut.requestToken();
        }
    }
    
    function auth2(oauth_verifier)
    {
        orkut.upgradeRequestToken(oauth_verifier);
        
        // this key is used to fetch unread scraps.
        localStorage['lastKey'] = '';
        
        // check
        checkIcon();
    }
    
    function checkIcon() {
        
        
        // change icon after auth
        if(localStorage['authenticated']=='1'){
            chrome.browserAction.setIcon({path: "icon19.png"});
        }
        
    }
    
    function logout() 
    {
        localStorage['authenticated']=null;
        localStorage['oauth_token']=null;
        localStorage['oauth_token_secret']=null;
    }
    
    // loginscript.js calls here
    function registerListeners() {
	    
        // register listener for login notifications
        chrome.extension.onRequest.addListener( function(request, sender, sendResponse) {
        
            // debug
            console.log(sender.tab ? "from a content script:" + sender.tab.url : "from the extension");

            if (request.type == "auth2") {
                auth2(request.verifier);
            }
            
        });
    }
    
    
    var scrapScreen = [];
    var lockScrap = false;
    var unreadCount=0;
    
    function apoller(force) {
        
        // simple locking checking
        if(!lockScrap) {
        
            var json;
            var scrapPool = [];
            lockScrap = true;
            
            // list based on our last scrap
            if( force == 1 )
                json = orkut.listScraps('','');
            else
                json = orkut.listScraps('',localStorage['lastKey']);
                
            console.log(json);
			
             // iterate our json
             $.each(json[0]['data']['list'], function() {
                scrapPool.push({'id': this.id, 
                                'user_id': this.fromUserId,
                                'user': this.fromUserProfile.name.givenName, 
                                'thumb': this.fromUserProfile.thumbnailUrl,
                                'time': this.time,
                                'body': this.body});
            });
            
            console.log('poller called, size=' + scrapPool.length);
            
            if(scrapPool.length > 0) {
                
                // sort per time - older first
                scrapPool.sort(function(a,b){ return a.time - b.time ; });
                
                // set last key
                localStorage['lastKey'] = scrapPool[ scrapPool.length - 1 ].id;
                
                // concat to the main array
                this.scrapScreen = this.scrapScreen.concat(scrapPool.slice());
                
            }
            
            // update
            unreadCount += scrapPool.length;
            
            // update badge
            chrome.browserAction.setBadgeText({text: '' + unreadCount});
            
            // unlock
            lockScrap = false;
        }
    }
    
    function clearPool() {
        //scrapPool.clear();
        unreadCount = 0;
        chrome.browserAction.setBadgeText({text: ''});
    }
    

  </script>
  </head>
  <body onload="initBg();">

  <!-- the message template -->
  <div id="Popup">
    <div id="Data" />
  </div>
  <!--- end message template -->
  </body>
</html>
